import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzPopconfirmModule } from 'ng-zorro-antd/popconfirm';
import { NzTableModule} from 'ng-zorro-antd/table';
import { NzModalModule } from 'ng-zorro-antd/modal';

interface ItemData {
  id: string;
  name: string;
  age: string;
  address: string;
}

@Component({
  selector: 'app-list2',
  standalone: true,
  imports: [
    FormsModule, 
    NzButtonModule, 
    NzInputModule, 
    NzPopconfirmModule, 
    NzTableModule,
    NzModalModule, 
    
  ],
  templateUrl:'./list2.component.html',
  styleUrl:'./list2.component.css' 
})
export class List2Component implements OnInit {

  i = 0;
  editId: string | null = null;
  listOfData: ItemData[] = [];

  isVisible = false;
  optionType = 'add';

  formObj: ItemData = {
    id: '',
    name: '',
    age: '',
    address: ''
  }

  handleOk() {
    console.log('this.formObj :', this.formObj);
    console.log('Button ok clicked!');
    if (this.optionType === 'add') {
      this.listOfData = [
        ...this.listOfData,
        {
          ...this.formObj
        }
      ];
    } else {
      let list: ItemData [] = []
      let formObj = JSON.parse(JSON.stringify(this.formObj))
      list = this.listOfData.map(element => {
        if (element.id === formObj.id) {
          return formObj
        } else {
          return element;
        }
      });
      this.listOfData = list;
    }
    this.isVisible = false;
    
    console.log('this.listOfData :', this.listOfData);
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }
  startEdit(id: string): void {
    this.editId = id;
  }

  stopEdit(): void {
    this.editId = null;
  }

  addRow(): void {
    this.formObj = {
      id: `${(new Date()).getTime()}`,
      name: '',
      age: '',
      address: ''
    }
    this.optionType = 'add';
    this.isVisible = true;
  }

  editRow(row: ItemData): void {
    this.optionType = 'edit';
    this.formObj = {...row}
    this.isVisible = true;
  }


  initData(): void {
    this.listOfData = [],//重置前先清空内容
    this.listOfData = [
      ...this.listOfData,
      {
        // id: `${this.i}`,
        // name: `Edward King ${this.i}`,
        // age: '32',
        // address: `London, Park Lane no. ${this.i}`
        id: '1',
        name: '彭露露',
        age: '23',
        address: '开封市'
      },
      {
        id: '2',
        name: '黄果果',
        age: '24',
        address: '开封市'
      }
      
    ];
    this.i++;
  }

  deleteRow(id: string): void {
    this.listOfData = this.listOfData.filter(d => d.id !== id);
  }

  ngOnInit(): void {
    this.initData();
  }
}